package com.alinesno.cloud.common.config;

import java.util.Properties;

import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.StandardPBEByteEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

/**
 * @Descripition : Jasypt安全框架加密类工具包
 * @author WeiXiaoJin
 * @since 2019年8月4日 下午10:21:11
 *
 */
public class JasyptUtils {
	
    private static Properties props ; 

	/**
    * 通过配置文件名读取内容
    * @param fileName
    * @return
    */
   static {
       try {
    	   String fileName = "application-base.yml" ; 
           Resource resource = new ClassPathResource(fileName);
           props = PropertiesLoaderUtils.loadProperties(resource);
       } catch (Exception e) {
           e.printStackTrace();
       }
   }
	
	/**
	 * Jasypt生成加密结果
	 *
	 * @param password 配置文件中设定的加密密码 jasypt.encryptor.password
	 * @param value    待加密值
	 * @return
	 */
	public static String encryptPwd(String value) {

		String password = props.getProperty("password") ; 
		
		PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
		SimpleStringPBEConfig config = new SimpleStringPBEConfig();
		config.setPassword(password);
		config.setAlgorithm("PBEWithMD5AndDES");
		config.setKeyObtentionIterations("1000");
		config.setPoolSize("1");
		config.setProviderName(null);
		config.setProviderClassName(null);
		config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
		config.setIvGeneratorClassName("org.jasypt.salt.NoOpIVGenerator");
		config.setStringOutputType("base64");
		encryptor.setConfig(config);
	
		return encryptor.encrypt(value) ;
	}

	/**
	 * 解密
	 *
	 * @param password 配置文件中设定的加密密码 jasypt.encryptor.password
	 * @param value    待解密密文
	 * @return
	 */
	public static String decyptPwd(String password, String value) {
		PooledPBEStringEncryptor encryptOr = new PooledPBEStringEncryptor();
		encryptOr.setConfig(cryptOr(password));
		String result = encryptOr.decrypt(value);
		return result;
	}

	public static SimpleStringPBEConfig cryptOr(String password) {
		SimpleStringPBEConfig config = new SimpleStringPBEConfig();
		config.setPassword(password);
		config.setAlgorithm(StandardPBEByteEncryptor.DEFAULT_ALGORITHM);
		config.setKeyObtentionIterations("1000");
		config.setPoolSize("1");
		config.setProviderName("SunJCE");
		config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
		config.setStringOutputType("base64");
		return config;
	}

}